import React from 'react';
import { connect } from 'react-redux'
import {Button, Table, Popover, Form, Modal, Input, Badge, Switch} from 'antd';
const FormItem = Form.Item;
import SearchArea from "components/search-area";
import CustomerQueryService from 'containers/setting/customer-type-define/customer-type-define.service'
import {messages} from "share/common";
import ResizeTable from "components/resize-table";

class CustomerTypeDefine extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      data: [],
      page: 0,
      pagination: {
        total: 0,
      },
      columns: [
        {
          title: messages('setting.key2153')/*客户类型代码*/ , dataIndex: 'customerTypeCode', render: (text) => {
            return (
              <Popover placement="topLeft" content={text}>{text}</Popover>
            )
          }
        },
        {
          title: messages('setting.key2154')/*客户类型名称*/, dataIndex: 'customerTypeName', render: (text) => {
            return (
              <Popover placement="topLeft" content={text}>{text}</Popover>
            )
          }
        },
        {
          title: messages('common.column.status')/*状态*/, dataIndex: 'enabled', render: enabled => (
            <Badge status={enabled ? 'success' : 'error'}
                   text={enabled ? messages('common.status.enable') : messages('common.status.disable')}/>
          )
        },
        {
          title: messages('common.operation')/*操作*/, dataIndex: 'operation', render: (text, record) => {
            return (
              <a onClick={(e) => this.onNewClick(e, text, record)}>编辑</a>
            )
          }
        },
      ],
      searchForm: [
        {
          type: 'input',
          id: 'code',
          label: messages('setting.key2153')/*客户类型代码*/
        },
        {
          type: 'input',
          id: 'name',
          label: messages('setting.key2154')/*客户类型名称*/
        },
      ],
      searchParams: {
        code: "",
        name: "",
      },
      visible: false,
      confirmLoading: false,
      record: {
        id: null,
        customerTypeCode: "",
        customerTypeName: "",
        enabled: true,
      }
    }
  }


  componentWillMount() {
    this.getTableData();
  }

  //获取映射关系
  getTableData = () => {
    const {page, searchParams} = this.state;
    this.setState({
      loading: true,
    });
    CustomerQueryService.getTableData(page, searchParams).then(res => {
        this.setState({
          loading: false,
          data: res.data || [],
          pagination: {
            total: Number(res.headers['x-total-count']) || 0,
            current: this.state.page + 1,
            onChange: this.onChangePaper,
          }
        });
    }
    ).catch(err => {
      this.setState({
        loading: false,
      });
    })
  };

  //点击分页
  onChangePaper = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({
          page: page - 1,
        }, () => {
          this.getTableData();
        }
      )
    }
  };

  //点击搜索
  search = (result) => {
    this.setState({
      page: 0,
      pagination: {
        total: 0,
      },
      searchParams: result,
    }, () => {
      this.getTableData();
    })
  };

  //点击清空
  clear = () => {
    this.setState({
      page: 0,
      pagination: {
        total: 0,
      },
      searchParams: {
        code: "",
        name: "",
      },
    }, () => {
      this.getTableData();
    })
  };

  onNewClick = (e, text, item) => {
    let record = {
      id: null,
      customerTypeCode: null,
      customerTypeName: null,
      enabled: true,
    };
    this.setState({
      record: item ? item : record,
      visible: true,
    }, () => {
      this.props.form.setFieldsValue(this.state.record);
    });
  };

  onOk = () => {
    const {record} = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if(!err){
        let params = Object.assign(record, values);
        if(record.id){
          this.editCustomerType(params);
        }else{
          this.addCustomerType(params);
        }
      }
    });
  };

  addCustomerType = (params) => {
    CustomerQueryService.addCustomerType(params).then(res => {
      this.setState({
        confirmLoading: false,
        visible: false,
      });
      this.getTableData();
      }
    ).catch(err => {
      this.getTableData();
      this.setState({
        confirmLoading: false,
      });
    })
  };

  editCustomerType = (params) => {
    CustomerQueryService.editCustomerType(params).then(res => {
      this.setState({
        confirmLoading: false,
        visible: false,
      });
      this.getTableData();
      }
    ).catch(err => {
      this.getTableData();
      this.setState({
        confirmLoading: false,
      });
    })
  };

  onCancel = () => {
    this.props.form.resetFields();
    this.setState({
      visible: false,
    });
  };


  render (){
    const {record, loading, data, columns, searchForm, confirmLoading, visible, pagination} = this.state;
    const {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: { span:6 },
      wrapperCol: { span:16 }
    };
    return(
      <div className={"customer-query"}>
        <SearchArea
          searchForm={searchForm}
          submitHandle={this.search}
          clearHandle={this.clear}
        />
        <Button onClick={this.onNewClick} type={"primary"}>{messages('common.create')/*新建*/}</Button>
        <div style={{margin: "10px 0"}}>
          {messages('setting.key1589',{arg1: pagination.total})/*共搜索到{arg1}条数据*/}
        </div>
        <Table rowKey={"customerTypeCode"}
               loading={loading}
               dataSource={data}
               columns={columns}
               pagination={pagination}
               size="middle"
               bordered/>
        <Modal title={record.id ? messages('setting.key2155')/*编辑客户类型*/ : messages('setting.key2156')/*新增客户类型*/}
               visible={visible}
               destroyOnClose={true}
               onOk={this.onOk}
               onCancel={this.onCancel}
               confirmLoading={confirmLoading}>
          <Form>
            <FormItem label={messages('common.column.status'/*状态*/)} {...formItemLayout}>
              {getFieldDecorator('enabled',{
                initialValue: record.enabled,
                valuePropName: "checked",
              })
              (<Switch/>)
              }
            </FormItem>
            <FormItem label={messages('setting.key2153')/*客户类型代码*/} {...formItemLayout}>
              {getFieldDecorator('customerTypeCode',{
                initialValue: record.customerTypeCode,
                rules: [{
                  required: true,
                  message: messages('setting.key2157')/*客户类型代码不能为空*/
                }]
              })
              (<Input placeholder={messages('common.please.enter')/* 请输入 */} disabled={!!record.id}/>)
              }
            </FormItem>
            <FormItem label={messages('setting.key2154')/*客户类型名称*/} {...formItemLayout}>
              {getFieldDecorator('customerTypeName',{
                initialValue: record.customerTypeName,
                rules: [{
                  required: true,
                  message: messages('setting.key2158')/*客户类型名称不能为空*/
                }]
              })
              (<Input placeholder={messages('common.please.enter')/* 请输入 */}/>)
              }
            </FormItem>
          </Form>
        </Modal>
      </div>
    )
  }
}


CustomerTypeDefine.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
  }
}

const wrappedCustomerTypeDefine = Form.create()(CustomerTypeDefine);
export default connect(mapStateToProps)(wrappedCustomerTypeDefine);
